<?php

class FormHelper {

    var $fields;
    var $data;
    var $error;
    
    function __construct($fields, $data) {
        $this->fields = $fields;
        $this->data = $data;

        foreach($this->fields as $field => $validation) {
            if (!isset($this->data[$field])) {
                $this->data[$field] = "";
            } else {
                $this->data[$field] = filter_var(trim($this->data[$field]),
                        FILTER_SANITIZE_SPECIAL_CHARS);
            }
        }
    }

    function validate() {
        $valid = true;
        
        foreach($this->fields as $field => $validation) {
            $validateFunction = "_validate_" . $validation;

            if (!$this->$validateFunction($this->data[$field], $error)) {
                $this->error[$field] = $error;
                $valid = false;
            }
        }

        return $valid;
    }

    function getError($field) {
        if (!empty($this->error[$field])) {
            return $this->error[$field];
        } else {
            return "";
        }
    }

    function getData($field) {
        if (!empty($this->data[$field])) {
            return $this->data[$field];
        } else {
            return "";
        }
    }

    function getRadioChecked($field, $value) {
        if ($this->data[$field] == $value) {
            return 'checked="checked"';
        } else {
            return "";
        }
    }

    function _validate_none($value, &$error) {
        return true;
    }

    function _validate_required($value, &$error) {
        if ($value == '') {
            $error = "Required.";
            return false;
        }

        return true;
    }
    
    function _validate_whole_number($value, &$error){
        $integer_validate_options = array('options' => array("min_range"=>0));
        if(!empty($value) && !filter_var($value, FILTER_VALIDATE_INT, $integer_validate_options)){
            $error = 'Valid whole number required.';
            return false;
        }
        
        return true;
    }
}
?>